package fda.base;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Structure represent a memory with limited size: <br>
 * use this class as Tuple[] mem = Memory.getInstance().getMemory();  from any class/method
 */
public class Memory2 {

	private static Memory2 theInstance = null;

	private final List<Block> memBlocks;

	private Memory2() {
		memBlocks = new ArrayList<Block>();
		for(int i = 0; i < Constants.MEMORY_SIZE_BLOCKS; i++) {
			memBlocks.add(new Block(null));
		}
	}

	/**
	 * @return List of blocks of memory<br>
	 * Blocks are empty so they must be replaced by valid blocks
	 */
	public List<Block> getMemBlocks() {
		return memBlocks;
	}
	
	/**
	 * @return singleton instance of memory.
	 */
	public static Memory2 getInstance() {
		if (theInstance == null) {
			theInstance = new Memory2();
		}

		return theInstance;
	}

	/**
	 * @param df 
	 * @return Array of tuples created from DiskFile
	 */
	public Tuple[] fillMemory(DiskFile2 df) {
		Tuple[] res = new Tuple[df.getTupleCount()];
		int blockCount = df.getBlockCount();
		Block bl = null;
		int offset = 0;
		
		for(int i = 0; i < blockCount; ++i){
			bl = df.getBlock(i);
			for(Tuple t : bl.getRecords()){
				res[offset++] = t;
			}
		}
		
		return res;
	}

	/**
	 * @param batchSize number of blocks
	 * @param df DiskFile to create for
	 * @return array with size BlockSize*batchSize
	 */
	public Tuple[] getMemBlock(int batchSize, DiskFile2 df) {
		return new Tuple[batchSize * df.getBlockSize()];
	}
}
